module(..., package.seeall)

local imgPath = "images/"
local myImages = {
	"jessica_100.jpg",
	"andy_100.jpg",
	"aya_100.jpg",
	"jessica_100.jpg",
	"jessica_100.jpg",
	"jessica_100.jpg",
	"jessica_100.jpg"
}
local index = 1

--====================================================================--
-- SCENE: LAB
--====================================================================--

new = function ( params )
	
	------------------
	-- Params
	------------------
	
	local vLabel = "- LAB -"
	local vReload = false
	local start_grid = 1
	--
	if type( params ) == "table" then
		--
		if type( params.label ) == "string" then
			vLabel = params.label
		end
		--
		if type( params.reload ) == "boolean" then
			vReload = params.reload
		end
		--
		if type( params.start_grid ) == "integer" then
			start_grid = params.start_grid
		else
			start_grid = 1
		end
		--
	end
	
	------------------
	-- Groups
	------------------
	
	local localGroup = display.newGroup()
	
	local dragGroup = display.newGroup();

	------------------
	-- Display Objects
	------------------
	
	local background = display.newImage( "background2.png" )
	local title = display.newText( vLabel, 0, 0, native.systemFontBold, 16 )
	
	offSetX = 160
	-- local qq = display.newImage( imgPath .. "jessica_600x900.jpg" )
	-- qq.x = 0 + offSetX
	-- qq.y = 0
	-- qq.width = 200
	-- qq.height = 300
	-- local qq2 = display.newImage( imgPath .. "ironman_200x300.jpg" )
	-- qq2.x = 100 + 2*offSetX
	-- qq2.y = 0
	-- local qq3 = display.newImage( imgPath .. "padukon_200x300.jpg" )
	-- qq3.x = 160 + 3*offSetX
	-- qq3.y = 0
	-- local qq4 = display.newImage( imgPath .. "hulk_200x300.jpg" )
	-- qq4.x = 260*3
	-- qq4.y = 0
	-- local qq5 = display.newImage( imgPath .. "hulk_200x300.jpg" )
	-- qq5.x = 260*4
	-- qq5.y = 0

	-- dragGroup:insert(qq)
	-- dragGroup:insert(qq2)
	-- dragGroup:insert(qq3)
	-- dragGroup:insert(qq4)
	-- dragGroup:insert(qq5)
	dragGroup.x = 0;
	dragGroup.y = 230;
	
	--grid
	itemWidth = 200
	itemHeight = 300
	unit_w = 200
	unit_h = 300
	gridGroup = display.newGroup()
	gridGroup.y = -150
	function makeTiles(rowcnt,colcnt,unit_w,unit_h,cellpadding,leftmargin,topmargin)
		
		for i = 1, rowcnt, 1 do
			for j = 1, colcnt, 1 do
				x = (j-1)*(unit_w + cellpadding)+leftmargin
				y = topmargin + (i-1)*(unit_h + cellpadding)
				local unit = display.newRect( x, y, unit_w, unit_h )
				unit.alpha = 0.1
				gridGroup:insert(unit)

			end
		end
	end
	function putGrid(row,column,img,grid,cellpadding,leftmargin,topmargin)
		local slotGrp = display.newGroup()
		slotGrp.x = (column-1)*(unit_w + cellpadding) + offSetX
		slotGrp.y = 150

		local  item = display.newImageRect( img, itemWidth, itemHeight )
		--item.x = (column-1)*(unit_w + cellpadding) + offSetX
		--item.y = 150
		slotGrp:insert(item)
		--sphere
		local magicSphere = display.newImage( imgPath .. "afro_samurai.png" )
		magicSphere.x = 0
		magicSphere.y = 170
		magicSphere.width = 210
		magicSphere.height = 50
		magicSphere.alpha = 0.7
		slotGrp:insert(magicSphere)

		grid:insert(slotGrp)
	end
	function putGridZero(row,column,img,grid,cellpadding,leftmargin,topmargin)
		local item
		
		local slotGrp = display.newGroup()
		slotGrp.x = (column-1)*(unit_w + cellpadding) + offSetX
		slotGrp.y = 150

		local item_touched = function ( event )
			if ( event.phase == "began" ) then
				print ("mula sentuh gergasi")
			elseif ( event.phase == "moved" ) then
				--item.alpha = 0.0
				print ("gergasi moved")
			elseif ( event.phase == "ended" or event.phase == "cancelled" ) then
				--item.alpha = 0.5
				print ("abisss")
			end

			print("monster touched")
			return true
			
		end
		item = display.newImageRect( img, itemWidth, itemHeight )
		--item.x = (column-1)*(unit_w + cellpadding) + offSetX
		--item.y = 150
		item.alpha = 0.5
		item:addEventListener( "touch" , item_touched )
		slotGrp:insert(item)

		--sphere
		local magicSphere = display.newImage( imgPath .. "afro_samurai.png" )
		magicSphere.x = 0
		magicSphere.y = 170
		magicSphere.width = 210
		magicSphere.height = 50
		magicSphere.alpha = 0.7
		slotGrp:insert(magicSphere)

		local qq_monster = display.newImage( imgPath .. "summon_48.png" )
		--qq_monster.x = display.contentWidth/2
		qq_monster.y = 0
		qq_monster.x = 0
		qq_monster.alpha = 0.7
		slotGrp:insert(qq_monster)
		
		grid:insert(slotGrp)
		
		local moveUp
		local moveDown
		function moveUp()
				--print("moveUp()")
				transition.to( qq_monster, { time=2000, delay=0, y=-50, onComplete=moveDown} )
		end
		 
		function moveDown()
				transition.to( qq_monster, { time=1000, delay=0, y=0, onComplete=moveUp} )
		end	
		--transition.to( qq_monster, { time=2000, delay=500, y=display.contentHeight/2+50, onComplete=moveUp} )
		moveUp()
		

	end
	function calcIndex(dist)
		-- 0, 320, 
		print (dist)
	end
	
	--makeTiles(1,5,200,300,60,60,0)
	--get monster_slot list from db
	local slotNo = 1;
	for row in db:nrows("SELECT * FROM monster_slot") do
		local text = row._id.." "..row._id
		if (row.is_unlock == 1) then
				putGrid(1,slotNo,imgPath .. row.monster_img_tmp,gridGroup,60,60,5)
		else
			putGridZero(1,slotNo,imgPath .. "goku_200x300.jpg",gridGroup,60,60,5)
		end
		slotNo = slotNo + 1
	end

--	putGrid(1,1,imgPath .. "therockk_200x300.jpg",gridGroup,60,60,5)
--	putGrid(1,2,imgPath .. "hulk_200x300.jpg",gridGroup,60,60,5)
--	putGridZero(1,2,imgPath .. "goku_200x300.jpg",gridGroup,60,60,5)
	--putGrid(1,3,imgPath .. "afro_samurai.png",gridGroup,60,60,5)
	--putGrid(1,3,imgPath .. "padukon_200x300.jpg",gridGroup,60,60,5)
--	putGrid(1,4,imgPath .. "ironman_200x300.jpg",gridGroup,60,60,5)
	--putGrid(1,5,imgPath .. "jessica_200x300.jpg",gridGroup,60,60,5)
--	putGrid(1,6,imgPath .. "chopra_200x300.jpg",gridGroup,60,60,5)
	
		for i=1,5,1 do
			maxrow=1
			maxcol=5
			r = math.ceil(i/maxrow) --what row?
			c = i - (r-1)*maxcol    --what column?
			--putGrid(r,c,myImages[i],gridGroup,60,60,5)
			print("row=",r ,"col=", c)
		end
	dragGroup:insert(gridGroup)
	
	local rainLight = display.newRect( 60, 80, 200, 350 )
	rainLight.alpha = 0.6
	
	function showRainLight()
	    local myclosure = function() transition.to(rainLight, { time=800, alpha=0.5}) end
		timeShowId = timer.performWithDelay(400, myclosure, 1)	
	end
	function hideRainLight()
	    local myclosure = function() transition.to(rainLight, { time=100, alpha=0.0}) end
		timeHideId = timer.performWithDelay(10, myclosure, 1)	
	end
	function scrollGrid(i)
		i = i-1
		--dragGroup.x = -(i*(260))  -- i*(itemWidth + cellpadding)
		tween = transition.to( dragGroup, {time=400, x=-(i*(260)) } )
		--transition.to(rainLight, { time=10, alpha=0})
		--transition.to(rainLight, { time=4000, alpha=1})
		showRainLight()
		--tween = transition.to( dragGroup, {time=400, x=-(i*(260)), transition=easing.outExpo } )
		--tween = transition.to( items[itemNum+1], {time=400, x=screenW*.5, transition=easing.outExpo } )
		--rainLight.alpha = 0.5
	end
	
	--back button
	local backbt_touched = function ( event )
		--background:removeEventListener( "touch" , touched )
		print("touched jessica")
		director:changeScene( "field", "moveFromLeft" )
		return true
	end
	local backbt = display.newImage(imgPath .. "arrow_left_48.png");
	backbt:addEventListener( "touch" , backbt_touched )
	backbt.x = 30
	backbt.y = 200	

	--go tower button
	local gotowerbt_touched = function ( event )
		--background:removeEventListener( "touch" , touched )
		print("touched gotower button")
		director:changeScene( "tower", "overFromRight" )
		return true
	end
	local gotowerbt = display.newImage(imgPath .. "arrow_right_48.png");
	gotowerbt:addEventListener( "touch" , gotowerbt_touched )
	gotowerbt.x = 290
	gotowerbt.y = 200

	local widget = require "widget"
	--summon button
	local function onSummonEvent( event )
		local btn = event.target
		if event.phase == "press" then
			print( "User has began pressing the button with id: " .. btn.id )
		elseif event.phase == "moved" then
			print( "User has dragged their finger while pressing the button." )
		elseif event.phase == "release" then
			print( "User has lifted finger from button." )        
		end
		return true;
	end
	local summonBtn = widget.newButton{
		id = "summonBtn",
		default =  imgPath .. "summon_32.png",
		over =  imgPath .. "ball_32.png",
		width = 32, height = 32,
		onEvent = onSummonEvent
	}
	summonBtn.x = 280
	summonBtn.y = 280

	--gacha button
	local function onGachaEvent( event )
		local btn = event.target
		if event.phase == "press" then
			print( "User has began pressing the button with id: " .. btn.id )
		elseif event.phase == "moved" then
			print( "User has dragged their finger while pressing the button." )
		elseif event.phase == "release" then
			print( "User has lifted finger from button." )        
		end
		return true;
	end
	local gachaBtn = widget.newButton{
		id = "gachaBtn",
		default =  imgPath .. "gacha_32.png",
		over =  imgPath .. "ball_32.png",
		width = 32, height = 32,
		onEvent = onGachaEvent
	}
	gachaBtn.x = 280
	gachaBtn.y = 320

	--mix button
	local function onMixEvent( event )
		local btn = event.target
		if event.phase == "press" then
			print( "User has began pressing the button with id: " .. btn.id )
		elseif event.phase == "moved" then
			print( "User has dragged their finger while pressing the button." )
		elseif event.phase == "release" then
			print( "User has lifted finger from button." )        
		end
		return true;
	end
	local mixBtn = widget.newButton{
		id = "mixBtn",
		default =  imgPath .. "mix_32.png",
		over =  imgPath .. "ball_32.png",
		width = 32, height = 32,
		onEvent = onMixEvent
	}
	mixBtn.x = 280
	mixBtn.y = 360

	--mission (quest) button
	local function onMissionEvent( event )
		local btn = event.target
		if event.phase == "press" then
			print( "User has began pressing the button with id: " .. btn.id )
		elseif event.phase == "moved" then
			print( "User has dragged their finger while pressing the button." )
		elseif event.phase == "release" then
			print( "User has lifted finger from button." )        
		end
		return true;
	end
	local missionBtn = widget.newButton{
		id = "missionBtn",
		default =  imgPath .. "missionButton.png",
		over =  imgPath .. "ball_32.png",
		width = 32, height = 32,
		onEvent = onMissionEvent
	}
	missionBtn.x = 50
	missionBtn.y = 350
	
	--inventory button
	local function onInventoryEvent( event )
		local btn = event.target
		if event.phase == "press" then
			print( "User has began pressing the button with id: " .. btn.id )
			director:changeScene( { back_scene="lab", start_grid=6 }, "inventory", "moveFromTop" )
		elseif event.phase == "moved" then
			print( "User has dragged their finger while pressing the button." )
		elseif event.phase == "release" then
			print( "User has lifted finger from button." )        
		end
		return true;
	end
	local inventoryBtn = widget.newButton{
		id = "inventoryBtn",
		default =  imgPath .. "inventory_72.png",
		over =  imgPath .. "ball_32.png",
		width = 72, height = 72,
		onEvent = onInventoryEvent
	}
	inventoryBtn.x = 160
	inventoryBtn.y = 50

	--deck button
	local function onDeckEvent( event )
		local btn = event.target
		if event.phase == "press" then
			print( "User has began pressing the button with id: " .. btn.id )
		elseif event.phase == "moved" then
			print( "User has dragged their finger while pressing the button." )
		elseif event.phase == "release" then
			print( "User has lifted finger from button." )        
		end
		return true;
	end
	local deckBtn = widget.newButton{
		id = "deckBtn",
		default =  imgPath .. "summon_32.png",
		over =  imgPath .. "ball_32.png",
		width = 32, height = 32,
		onEvent = onDeckEvent
	}
	deckBtn.x = 280
	deckBtn.y = 70
	
	if (1 ~= 1) then
		print("xxxxxxxxxxx=", start_grid)
	end
	scrollGrid(start_grid)

	levelBar.displayLevelBar()
	
	--start sprite
	local baseline = 300
	-- A sprite sheet with a green dude
	--local sheet2 = graphics.newImageSheet( "greenman.png", { width=128, height=128, numFrames=15 } )
	---local sheet2 = graphics.newImageSheet( "finalflyingdragon.png", { width=96, height=96, numFrames=16 } )


	-- play 15 frames every 500 ms
	---local instance2 = display.newSprite( sheet2, { name="man", start=1, count=16, time=3000 } )
	---instance2.x = display.contentWidth/2
	---instance2.y = baseline - 55
	---instance2:play()

	---instance2:addEventListener( "touch", onDeckEvent )
	--end aprite
	
--	local qq_monster = display.newImage( imgPath .. "summon_48.png" )
--	qq_monster.x = display.contentWidth/2
--	qq_monster.y = baseline
	--qqTween = transition.to( qq_monster, {time=400, y=350} )

	 
--	local moveUp
--	local moveDown
--	function moveUp()
			--print("moveUp()")
--			transition.to( qq_monster, { time=2000, delay=0, y=display.contentHeight/2-50, onComplete=moveDown} )
--	end
	 
--	function moveDown()
			transition.to( qq_monster, { time=2000, delay=0, y=display.contentHeight/2, onComplete=moveUp} )
--	end	
	--transition.to( qq_monster, { time=2000, delay=500, y=display.contentHeight/2+50, onComplete=moveUp} )
--	moveUp()


	

	-- local button = widget.newButton{
		-- label = "The Button",
		-- font = "HelveticaNeue-Bold",
		-- default =  imgPath .. "btn_bg.png",
		-- fontSize = 16
	-- }
	-- button.x = display.contentCenterX
	-- button.y = display.contentCenterY

	
	--====================================================================--
	-- BUTTONS
	--====================================================================--
	
	------------------
	-- Functions
	------------------
	
	local bt01t = function ( event )
		if event.phase == "release" then
			director:changeScene( "field", "moveFromLeft" )
			return true
		end
	end
	--
	local bt02t = function ( event )
		if event.phase == "release" then
			director:changeScene( "tower", "overFromRight" )
			return true
		end
	end
	
	------------------
	-- UI Objects
	------------------
		
	
	
	------------------
	-- Listeners
	------------------
	
	local touched_old = function ( event )
		if event.phase == "ended" then
			if vReload then
				director:changeScene( { label="Scene Reloaded" }, "screen2","moveFromRight" )
			else
				director:changeScene( "screen1", "crossfade" )
			end
		end
	end
	local touched = function ( event )
		if ( event.phase == "began" ) then
			print("slides", event.phase)
            -- Subsequent touch events will target button even if they are outside the contentBounds of button
			startPos = event.x
			prevPos = event.x
			
		elseif event.phase == "ended" then
			print("bg dragged")
			dragGroup.x = dragGroup.x - 20
		end
	end
	function touchListener (self, touch) 
		local phase = touch.phase
		local startDragX,endDragX
		
		print("slides", phase)
		if ( phase == "began" ) then
            -- Subsequent touch events will target button even if they are outside the contentBounds of button
            display.getCurrentStage():setFocus( self )
            self.isFocus = true
			startDragX = dragGroup.x
			print("startDragX : " , startDragX)

			startPos = touch.x
			prevPos = touch.x
												
        elseif( self.isFocus ) then
        
			if ( phase == "moved" ) then
				--rainLight.alpha = 0.0
				hideRainLight()
				local delta = touch.x - prevPos
				xDistance =  math.abs(touch.x - startPos)
				prevPos = touch.x
				
				dragGroup.x = dragGroup.x + delta
				

			elseif ( phase == "ended" or phase == "cancelled" ) then
				rainLight.alpha = 0.5
				dragDistance = touch.x - startPos
				print("dragDistance: " .. dragDistance)
				endDragX = dragGroup.x
				print("endDragX : " , endDragX)
				
				if (xDistance < 160) then
					if (touch.x > startPos) then
						print("swipe right")
						if (index == 1) then
							scrollGrid(1)
						else
							index = index - 1
							scrollGrid(index)
						end
						
					else
						print("swipe left")
						if (index == 6) then
							scrollGrid(index)
						else
							index = index + 1
							scrollGrid(index)
						end
					end
				else
					 if (touch.x > startPos) then
						print ("swipe long right")
						if (index == 1) then
							scrollGrid(1)
						else
							--index = index + math.abs(math.round(dragDistance/320))
							index = index - 1
							scrollGrid(index)
						end
					else
						print ("swipe long left")
						if (index == 6) then
							scrollGrid(6)
						else
							--index = index + math.abs(math.round(dragDistance/320))
							index = index + 1
							scrollGrid(index)
						end
						-- scrollGrid(6)
					end
				end
				
				
				
				--scrollGrid(6)
				

									
				if ( phase == "cancelled" ) then		
					print("moved cancelled")
				end

                -- Allow touch events to be sent normally to the objects they "hit"
                display.getCurrentStage():setFocus( nil )
                self.isFocus = false
														
			end
		end
					
		return true
		
	end
	
	--====================================================================--
	-- INITIALIZE
	--====================================================================--
	
	local initVars = function ()
		
		------------------
		-- Inserts
		------------------
		
		localGroup:insert( background )
		localGroup:insert( dragGroup )
		localGroup:insert( title )
		localGroup:insert( backbt )
		localGroup:insert( gotowerbt )
		

				
		------------------
		-- Positions
		------------------
		
		title.x = 160
		title.y = 5
		
		------------------
		-- Colors
		------------------
		
		title:setTextColor( 255,255,255 )
		
		------------------
		-- Listeners
		------------------
		
		--background:addEventListener( "touch" , touched )
		background.touch = touchListener
		background:addEventListener( "touch", background )
		
	end
	
	------------------
	-- Initiate variables
	------------------
	
	initVars()
	
	------------------
	-- MUST return a display.newGroup()
	------------------
	
	return localGroup
	
end
